﻿using FRMS.BUS;
using FRMS.DAL;
using FRMS.Model;
using FRMS.WebSockets;
using FRMS_N71SP.Model;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace FRMS.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class DeviceInteractionController : ControllerBase
    {
        public static int datanum_cur = 0;
        public static int datacount = 0;
        private readonly IHostingEnvironment _hostingEnvironment;

        public DeviceInteractionController(IHostingEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }

        /// <summary>
        /// 设备注册
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("DeviceRegister")]
        public registerReturn DeviceRegister(JLRegisterInfo jLRegister)
        {
            registerReturn reg = new registerReturn();
            registerMessage regM = new registerMessage();
            ModbusRtu rdata = new ModbusRtu();
            try
            {
                string deviceid = jLRegister.Data.DeviceInfo.DeviceIP;

                DeviceDAL deviceDAL = new DeviceDAL();
                //string session = jLRegister.UUID + "_" + jLRegister.TimeStamp;
                string[] ip_arr = jLRegister.Data.DeviceInfo.DeviceIP.Split('.');
                string session = "fx" + ip_arr[0].PadLeft(3, '0') + ip_arr[1].PadLeft(3, '0') + ip_arr[2].PadLeft(3, '0') + ip_arr[3].PadLeft(3, '0') + DateTime.Now.ToString("yyyyMMdd");
                bool result = deviceDAL.UpdateSession(jLRegister.DeviceId, jLRegister.Data.DeviceInfo.DeviceIP, session, jLRegister.UUID, jLRegister.Data.DeviceInfo.DeviceMac);
                if (result)
                {
                    RecordDAL recordDAL = new RecordDAL();
                    recordDAL.InsertDeviceRecord(jLRegister.UUID, jLRegister.DeviceId, jLRegister.Data.DeviceInfo.DeviceIP, "在线");
                    reg.Name = "registerResponse";
                    reg.TimeStamp = jLRegister.TimeStamp;
                    regM.Session = session;
                    regM.ServerVersion = "1.1.0";
                    regM.heartbeatData = rdata.GetheartbeatToDevices();
                    //regM.frequency = Convert.ToInt32(CommVars.Configuration.GetSection("IntervalTime").Value);
                    regM.frequency = Convert.ToInt32(AppSettingsHelper.Configuration["IntervalTime"]);
                    reg.Data = regM;
                    if (DataDownLoad.device_dic.ContainsKey(deviceid))
                    {
                        DataDownLoad.device_dic.Remove(deviceid);
                    }
                    DataDownLoad.device_dic.Add(deviceid, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    reg.Code = 1;
                    DataDownLoad.UpdateRegisterFlag(jLRegister.UUID, true);

                    try
                    {
                        //同步时间
                        TimeSynchronization timeSynchronization = new TimeSynchronization();
                        timeSynchronization.Name = "timeSynchronizationRequest";
                        timeSynchronization.Session = session;
                        timeSynchronization.UUID = jLRegister.UUID;
                        timeSynchronization.TimeStamp = GetTimeStamp();
                        TimeSynchronizationData timeSynchronizationData = new TimeSynchronizationData();
                        timeSynchronizationData.TimeMode = 1;
                        timeSynchronizationData.LocalTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        timeSynchronization.Data = timeSynchronizationData;
                        string k = JsonConvert.SerializeObject(timeSynchronization);
                        string re = HttpClientPost("http://" + jLRegister.Data.DeviceInfo.DeviceIP + ":8011/Request", timeSynchronization);
                    }
                    catch
                    {

                    }
                }
                else
                {
                    reg.Code = 0;
                }

                
                

                //下发485心跳数据
                //ApplyJLBUS BUS = new ApplyJLBUS();
                //bool flg = BUS.Heartbead485msg(jLRegister);
            }
            catch (Exception e)
            {
                reg.Message = e.ToString();
            }
            return reg;
        }


        /// <summary>
        /// 设备心跳
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("Heartbeat")]
        public HeartbeatReturn Heartbeat(JLHeartbeatInfo jLHeartbeat)
        {
            HeartbeatReturn reg = new HeartbeatReturn();
            try
            {
                string deviceid = jLHeartbeat.Data.DeviceInfo.DeviceIP;
                if (DataDownLoad.device_dic.ContainsKey(deviceid))
                {
                    DataDownLoad.device_dic.Remove(deviceid);
                }
                DataDownLoad.device_dic.Add(deviceid, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                reg.Name = "heartbeatResponse";
                reg.TimeStamp = GetTimeStamp();
                reg.Session = jLHeartbeat.Session;
                reg.EventCount = 0;
                if (DataDownLoad.register_dic.ContainsKey(jLHeartbeat.UUID))
                {
                    bool result = DataDownLoad.register_dic[jLHeartbeat.UUID];
                    if (!result)
                    {
                        /* bool re = SetTimePeriod(jLHeartbeat.UUID);
                         if (re)
                         {
                             bool re2 = SetPersonsTime(jLHeartbeat.UUID);
                         }*/
                        reg.Code = 1001;
                    }
                    else
                    {
                        reg.Code = 1;
                    }
                }
                else
                {
                    reg.Code = 1001;
                }
            }
            catch (Exception e)
            {

            }
            return reg;
        }

        /// <summary>
        /// 获取通行记录总数
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("GetHistoryCount")]
        public ResponseMessage GetHistoryCount(JLHistoryCondition jLHistoryCondition)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                DeviceDAL deviceDAL = new DeviceDAL();
                DeviceInfo deviceInfo = deviceDAL.LoadDeviceByIp(jLHistoryCondition.DeviceIp);
                JLHistoryRecord jLHistoryRecord = new JLHistoryRecord();
                jLHistoryRecord.Name = "historyRecordRequest";
                jLHistoryRecord.UUID = deviceInfo.DeviceNO;
                jLHistoryRecord.TimeStamp = GetTimeStamp();
                jLHistoryRecord.Session = deviceInfo.Session;
                JLHistoryRecordData jLHistoryRecordData = new JLHistoryRecordData();
                jLHistoryRecordData.BeginTime = jLHistoryCondition.StartTime;
                jLHistoryRecordData.EndTime = jLHistoryCondition.EndTime;
                if (jLHistoryCondition.UUid != "")
                {
                    jLHistoryRecordData.SearchType = 1;
                    jLHistoryRecordData.PersonId = jLHistoryCondition.UUid;
                }
                jLHistoryRecordData.Action = 3;
                jLHistoryRecord.Data = jLHistoryRecordData;
                string re = HttpClientPost("http://" + jLHistoryCondition.DeviceIp + ":8011/Request", jLHistoryRecord);
                JLHistoryRecordReturn jLHistoryRecordReturn = JsonConvert.DeserializeObject<JLHistoryRecordReturn>(re);
                datacount = jLHistoryRecordReturn.Data.Total;
                message.errcode = 0;
                message.data = jLHistoryRecordReturn.Data.Total;
            }
            catch (Exception e)
            {
                message.errcode = 1;
            }
            return message;
        }

        /// <summary>
        /// 通行记录下载
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("GetHistoryDownLoad")]
        public ResponseMessage GetHistoryDownLoad(JLHistoryCondition jLHistoryCondition)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                DeviceDAL deviceDAL = new DeviceDAL();
                DeviceInfo deviceInfo = deviceDAL.LoadDeviceByIp(jLHistoryCondition.DeviceIp);
                DataDownLoad.list.Clear();
                datacount = 0;
                datanum_cur = 0;
                JLHistoryRecord jLHistoryRecord = new JLHistoryRecord();
                jLHistoryRecord.Name = "historyRecordRequest";
                jLHistoryRecord.UUID = deviceInfo.DeviceNO;
                jLHistoryRecord.TimeStamp = GetTimeStamp();
                jLHistoryRecord.Session = deviceInfo.Session;
                JLHistoryRecordData jLHistoryRecordData = new JLHistoryRecordData();
                jLHistoryRecordData.BeginTime = jLHistoryCondition.StartTime;
                jLHistoryRecordData.EndTime = jLHistoryCondition.EndTime;
                if (jLHistoryCondition.UUid != "")
                {
                    jLHistoryRecordData.SearchType = 1;
                    jLHistoryRecordData.PersonId = jLHistoryCondition.UUid;
                }
                jLHistoryRecordData.Action = 1;
                jLHistoryRecord.Data = jLHistoryRecordData;
                string re = HttpClientPost("http://" + jLHistoryCondition.DeviceIp + ":8011/Request", jLHistoryRecord);
                JLHistoryRecordReturn jLHistoryRecordReturn = JsonConvert.DeserializeObject<JLHistoryRecordReturn>(re);
                if (jLHistoryRecordReturn.Code == 1)
                {
                    bool result = true;
                    while (result)
                    {
                        if (datanum_cur == datacount)
                        {
                            HistoryCount historyCount = new HistoryCount();
                            historyCount.HistoryNum = datanum_cur;
                            historyCount.LoadState = 1;
                            PushMessage(historyCount);
                            result = false;
                        }
                        else
                        {
                            int state = GetHistoryState(jLHistoryCondition, deviceInfo.Session);
                            if (state == 0)
                            {
                                HistoryCount historyCount = new HistoryCount();
                                historyCount.HistoryNum = datanum_cur;
                                historyCount.LoadState = 1;
                                PushMessage(historyCount);
                                result = false;
                            }
                            else
                            {
                                Thread.Sleep(1000);
                            }
                        }
                    }

                    message.errcode = 0;
                    List<HistoryInfo> histories = new List<HistoryInfo>();
                    histories = DataDownLoad.list;
                    message.data = histories;
                    datacount = 0;
                }
                else
                {
                    DataDownLoad.list.Clear();
                    datacount = 0;
                    message.errcode = 1;
                    message.errmsg = jLHistoryRecordReturn.Message;
                }

            }
            catch (Exception e)
            {
                message.errcode = 1;
            }
            return message;
        }

        [HttpPost]
        [Route("HistoryDownLoad")]
        public ResponseMessage HistoryDownLoad(JLHistoryCondition jLHistoryCondition)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                DeviceDAL deviceDAL = new DeviceDAL();
                DeviceInfo deviceInfo = deviceDAL.LoadDeviceByIp(jLHistoryCondition.DeviceIp);
                DataDownLoad.list.Clear();
                datanum_cur = 0;
                datacount = 0;
                JLHistoryRecord jLHistoryRecord = new JLHistoryRecord();
                jLHistoryRecord.Name = "historyRecordRequest";
                jLHistoryRecord.UUID = deviceInfo.DeviceNO;
                jLHistoryRecord.TimeStamp = GetTimeStamp();
                jLHistoryRecord.Session = deviceInfo.Session;
                JLHistoryRecordData jLHistoryRecordData = new JLHistoryRecordData();
                jLHistoryRecordData.BeginTime = jLHistoryCondition.StartTime;
                jLHistoryRecordData.EndTime = jLHistoryCondition.EndTime;
                if (jLHistoryCondition.UUid != "")
                {
                    jLHistoryRecordData.SearchType = 1;
                    jLHistoryRecordData.PersonId = jLHistoryCondition.UUid;
                }
                jLHistoryRecordData.Action = 1;
                jLHistoryRecord.Data = jLHistoryRecordData;
                string re = HttpClientPost("http://" + jLHistoryCondition.DeviceIp + ":8011/Request", jLHistoryRecord);
                JLHistoryRecordReturn jLHistoryRecordReturn = JsonConvert.DeserializeObject<JLHistoryRecordReturn>(re);
                if (jLHistoryRecordReturn.Code == 1)
                {
                    datacount = jLHistoryRecordReturn.Data.Total;
                    bool result = true;
                    while (result)
                    {
                        if (datanum_cur == datacount)
                        {
                            HistoryCount historyCount = new HistoryCount();
                            historyCount.HistoryNum = datanum_cur;
                            historyCount.LoadState = 1;
                            historyCount.Total = datacount;
                            PushMessage(historyCount);
                            result = false;
                        }
                        else
                        {
                            int state = GetHistoryState(jLHistoryCondition, deviceInfo.Session);
                            if (state == 0)
                            {
                                HistoryCount historyCount = new HistoryCount();
                                historyCount.HistoryNum = datanum_cur;
                                historyCount.LoadState = 1;
                                historyCount.Total = datacount;
                                PushMessage(historyCount);
                                result = false;
                            }
                            else
                            {
                                Thread.Sleep(1000);
                            }
                        }
                    }

                    message.errcode = 0;
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = jLHistoryRecordReturn.Message;
                }
            }
            catch (Exception e)
            {
                message.errcode = 1;
                message.errmsg = "下载异常";
            }
            return message;
        }

        /// <summary>
        /// 查看下载记录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("GetHistoryList")]
        public ResponseMessage GetHistoryList()
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                message.errcode = 0;
                message.data = DataDownLoad.list;
            }
            catch (Exception e)
            {
                message.errcode = 1;
                message.errmsg = "查看下载内容异常";
            }
            return message;
        }

        public string HttpClientPost(string url, object datajson)
        {
            HttpClient httpClient = new HttpClient();//http对象
            //表头参数
            httpClient.DefaultRequestHeaders.Accept.Clear();
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            //转为链接需要的格式
            HttpContent httpContent = new JsonContent(datajson);
            //请求
            HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
            if (response.IsSuccessStatusCode)
            {
                Task<string> t = response.Content.ReadAsStringAsync();
                if (t != null)
                {
                    return t.Result;
                }
            }
            return "";
        }

        /// <summary>
        /// 设备上传通行记录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("HistoryLoad")]
        public HistoryInfoDownLoadReturn HistoryLoad(JLHistoryRecordLoad jLHistoryRecord)
        {
            HistoryInfoDownLoadReturn reg = new HistoryInfoDownLoadReturn();
            try
            {
                HistoryInfo history = new HistoryInfo();
                history.Name = jLHistoryRecord.Data.CompareInfo.PersonInfo.PersonName;
                history.UUid = jLHistoryRecord.Data.CompareInfo.PersonInfo.PersonId;
                history.UpdateTime = jLHistoryRecord.Data.CompareInfo.CompareTime;
                if (jLHistoryRecord.Data.VerifyData.ICCardVerify == 1)
                {
                    history.Type = "刷卡";
                }
                else if (jLHistoryRecord.Data.VerifyData.IDCardVerify == 1)
                {
                    history.Type = "身份证";
                }
                else if (jLHistoryRecord.Data.VerifyData.PasswordVerify == 1)
                {
                    history.Type = "密码";
                }
                else if (jLHistoryRecord.Data.VerifyData.PersonListVerify == 1)
                {
                    history.Type = "人脸";
                }
                if (jLHistoryRecord.Data.VerifyData.VerifyStatus == 1)
                {
                    history.Result = "成功";
                }
                else
                {
                    history.Result = "失败";
                }

                DataDownLoad.list.Add(history);
                datanum_cur++;
                HistoryCount historyCount = new HistoryCount();
                historyCount.HistoryNum = datanum_cur;
                historyCount.Total = datacount;
                PushMessage(historyCount);
                reg.Name = "recordInfoResponse";
                reg.Session = jLHistoryRecord.Session;
                reg.Code = 1;
                reg.TimeStamp = GetTimeStamp();
                reg.Message = "";
            }
            catch (Exception e)
            {
                reg.Name = "recordInfoResponse";
                reg.Session = jLHistoryRecord.Session;
                reg.Code = 1;
                reg.TimeStamp = GetTimeStamp();
                reg.Message = "";
            }
            return reg;
        }

        public int GetHistoryState(JLHistoryCondition jLHistoryCondition, string session)
        {
            try
            {
                JLHistoryRecord jLHistoryRecord = new JLHistoryRecord();
                jLHistoryRecord.Name = "historyRecordRequest";
                jLHistoryRecord.UUID = jLHistoryCondition.UUid;
                jLHistoryRecord.TimeStamp = 111111;
                jLHistoryRecord.Session = session;
                JLHistoryRecordData jLHistoryRecordData = new JLHistoryRecordData();
                jLHistoryRecordData.BeginTime = jLHistoryCondition.StartTime;
                jLHistoryRecordData.EndTime = jLHistoryCondition.EndTime;
                if (jLHistoryCondition.UUid != "")
                {
                    jLHistoryRecordData.SearchType = 1;
                    jLHistoryRecordData.PersonId = jLHistoryCondition.UUid;
                }
                jLHistoryRecordData.Action = 0;
                jLHistoryRecord.Data = jLHistoryRecordData;
                string re = HttpClientPost("http://" + jLHistoryCondition.DeviceIp + ":8011/Request", jLHistoryRecord);
                JLHistoryRecordReturn jLHistoryRecordReturn = JsonConvert.DeserializeObject<JLHistoryRecordReturn>(re);
                return jLHistoryRecordReturn.Data.Status;
            }
            catch (Exception e)
            {
                return 1;
            }
        }

        public static async Task<bool> PushMessage(HistoryCount historyCount)
        {
            try
            {
                string Msg = JsonConvert.SerializeObject(historyCount);
                List<WebSocket> web = WebSocketMiddleware._sockets;

                if (web != null)
                {
                    foreach (var item in web)
                    {
                        try
                        {
                            if (item.State.ToString() == "Closed")
                            {
                                WebSocketMiddleware.RemoveSocket(item);
                            }
                            else
                            {
                                byte[] bMessage = Encoding.UTF8.GetBytes(Msg);
                                await item.SendAsync(new ArraySegment<byte>(bMessage), WebSocketMessageType.Text, true, new CancellationToken());
                            }
                        }
                        catch (Exception ex)
                        {
                            continue;
                        }
                    }
                }
                return true;
            }
            catch
            {
                return true;
            }
        }

        /// <summary>
        /// 获取时间戳
        /// </summary>
        /// <returns></returns>
        public int GetTimeStamp()
        {
            TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt32(ts.TotalSeconds);
        }

        /// <summary>
        /// 导出通行记录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("ExportHistory")]
        public ResponseMessage ExportHistory()
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                string path = _hostingEnvironment.WebRootPath + "/Export";
                string sFileName = "通行记录.xlsx";

                FileInfo file = new FileInfo(Path.Combine(path, sFileName));

                file.Delete();
                ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                using (ExcelPackage package = new ExcelPackage(file))

                {
                    // 添加worksheet

                    ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("通行记录");

                    //添加头
                    worksheet.Cells[1, 1].Value = "记录编号";
                    worksheet.Cells[1, 2].Value = "姓名";
                    worksheet.Cells[1, 3].Value = "业主编号";
                    worksheet.Cells[1, 4].Value = "验证时间";
                    worksheet.Cells[1, 5].Value = "验证方式";
                    worksheet.Cells[1, 6].Value = "验证结果";

                    //添加值
                    List<HistoryInfo> list = DataDownLoad.list;
                    int i = 1;
                    foreach (var item in list)
                    {
                        worksheet.Cells[i + 2, 1].Value = i;
                        worksheet.Cells[i + 2, 2].Value = item.Name;
                        worksheet.Cells[i + 2, 3].Value = item.UUid;
                        worksheet.Cells[i + 2, 4].Value = item.UpdateTime;
                        worksheet.Cells[i + 2, 5].Value = item.Type;
                        worksheet.Cells[i + 2, 6].Value = item.Result;
                        i++;
                    }
                    package.Save();

                }
                message.errcode = 0;
                message.errmsg = "";
                message.data = "/Export/" + sFileName;

            }
            catch (Exception e)
            {
                DataClearBUS dataClearBUS = new DataClearBUS();
                ErrorLog errorLog = new ErrorLog();
                errorLog.ErrorMsg = e.ToString();
                errorLog.Operation = "导出记录";
                dataClearBUS.AddErrorLog(errorLog);
                message.errcode = 1;
                message.errmsg = "导出异常";
            }
            return message;
        }

        [HttpPost]
        [Route("SetTimePeriod")]
        public bool SetTimePeriod(string uuid)
        {
            try
            {
                //string mode = CommVars.Configuration.GetSection("TimeMode").Value;
                string mode = AppSettingsHelper.Configuration["TimeMode"];
                bool result;
                DeviceDAL deviceDAL = new DeviceDAL();
                DeviceInfo deviceInfo = deviceDAL.LoadDeviceByUUID(uuid);
                JLTimeTable jLTimeTable = new JLTimeTable();
                jLTimeTable.Name = "setTimeTableRequest";
                jLTimeTable.UUID = uuid;
                jLTimeTable.Sign = "";
                jLTimeTable.Session = deviceInfo.Session;
                jLTimeTable.TimeStamp = GetTimeStamp();
                JLTimeTableData jLTimeTableData = new JLTimeTableData();
                List<JLTimeTableTimeTable> list = new List<JLTimeTableTimeTable>();
                JLTimeTableTimeTable jLTimeTableTimeTable = new JLTimeTableTimeTable();
                jLTimeTableTimeTable.Index = 1;
                if (mode == "1")
                {
                    jLTimeTableTimeTable.StartDate = "2022-01-01";
                    jLTimeTableTimeTable.EndDate = "2037-12-31";
                }
                else
                {
                    DateTime AssemblDate = Convert.ToDateTime(DateTime.Now.AddYears(-1).Year + "-" + "01" + "-" + "01");
                    jLTimeTableTimeTable.StartDate = AssemblDate.ToString("yyyy-MM-dd");
                    jLTimeTableTimeTable.EndDate = AssemblDate.AddYears(16).AddDays(-1).ToString("yyyy-MM-dd");
                }
                jLTimeTableTimeTable.BeginTime = "00:00";
                jLTimeTableTimeTable.EndTime = "23:59";
                jLTimeTableTimeTable.DateEnable = 1;
                jLTimeTableTimeTable.Monday = 1;
                jLTimeTableTimeTable.Tuesday = 1;
                jLTimeTableTimeTable.Wednesday = 1;
                jLTimeTableTimeTable.Thursday = 1;
                jLTimeTableTimeTable.Friday = 1;
                jLTimeTableTimeTable.Saturday = 1;
                jLTimeTableTimeTable.Sunday = 1;
                list.Add(jLTimeTableTimeTable);
                jLTimeTableData.Table = list;
                jLTimeTable.Data = jLTimeTableData;
                string re = HttpClientPost("http://" + deviceInfo.DeviceIP + ":8011/Request", jLTimeTable);
                JLTimeTableReturn jLTimeTableReturn = JsonConvert.DeserializeObject<JLTimeTableReturn>(re);
                if (jLTimeTableReturn.Code == 1)
                {
                    result = true;
                }
                else
                {
                    result = false;
                }
                return result;
            }
            catch
            {
                return true;
            }
        }

        [HttpPost]
        [Route("SetPersonsTime")]
        public bool SetPersonsTime(string uuid)
        {
            try
            {
                bool result;
                DeviceDAL deviceDAL = new DeviceDAL();
                DeviceInfo deviceInfo = deviceDAL.LoadDeviceByUUID(uuid);
                JLPersonsTime jLPersonsTime = new JLPersonsTime();
                jLPersonsTime.Name = "setPersonsTimeRequest";
                jLPersonsTime.UUID = uuid;
                jLPersonsTime.Sign = "";
                jLPersonsTime.Session = deviceInfo.Session;
                jLPersonsTime.TimeStamp = GetTimeStamp();
                result = true;
                for (int i = 1; i < 5; i++)
                {
                    JLPersonsTimeData jLPersonsTimeData = new JLPersonsTimeData();
                    jLPersonsTimeData.PersonIdentity = i;
                    int[] arry = { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
                    jLPersonsTimeData.TimeTable = arry;
                    jLPersonsTime.Data = jLPersonsTimeData;
                    string re = HttpClientPost("http://" + deviceInfo.DeviceIP + ":8011/Request", jLPersonsTime);
                    JLTimeTableReturn jLTimeTableReturn = JsonConvert.DeserializeObject<JLTimeTableReturn>(re);
                    if (jLTimeTableReturn.Code != 1)
                    {
                        result = false;
                        break;
                    }
                }

                return result;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// test
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("Test")]
        public ResponseMessage Test(object kk)
        {
            ResponseMessage message = new ResponseMessage();
            LogHelper.Log(kk.ToString());
            return message;
        }

        /// <summary>
        /// N71SP设备心跳
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("N71SPHeartbeat")]
        public HeartbeatReturn N71SPHeartbeat(N71SPHeartbeatInfo jLHeartbeat)
        {
            HeartbeatReturn reg = new HeartbeatReturn();
            try
            {
                string deviceid = jLHeartbeat.DeviceID;
                if (DataDownLoad.device_dic.ContainsKey(deviceid))
                {
                    DataDownLoad.device_dic.Remove(deviceid);
                }
                DataDownLoad.device_dic.Add(deviceid, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            }
            catch (Exception e)
            {

            }
            return reg;
        }

        /// <summary>
        /// N71SP认证记录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("N71SPRecord")]
        public string N71SPRecord(N71SPRecordinfo n71SPRecordinfo)
        {
            try
            {
                string deviceid = n71SPRecordinfo.DeviceID;
            }
            catch (Exception e)
            {
                return "";
            }
            return "";
        }
    }
}
